package org.candan.spider.task.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

import org.apache.log4j.Logger;
import org.candan.spider.util.DateUtil;
import org.candan.spider.util.SLog;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;


public abstract class XMLParseAbstract {


	protected Logger logger = new SLog("XML解析").getLogger(); 
	
	/**
	 * @category 加载xml文件
	 * @param file
	 * @return
	 * @throws DocumentException
	 */
	public Document readXML(String file)  {
		SAXReader saxReader = new SAXReader();
		try {
			return saxReader.read(file);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * @category xml序列化
	 * @return
	 */
	public boolean serialize(Document doc, String path){
		XMLWriter output = null;
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		try {
			output = new XMLWriter( new FileOutputStream(path),format);
			output.write(doc);
			output.flush();
			output.close();
			logger.info("文件序列化完成");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * @category 获取xml数值对象(将xml中数值与Java对象类型进行转换)
	 * @param <T> 
	 * @param clas 数值类型
	 * @param el 节点
	 * @param key 子节点路径名称
	 * @return
	 */
	public <T> T selectSingleNodeValue(Class<T> clas, Element el, String key) {
		Node node = el.selectSingleNode(key);
		T res = null;
		if(clas == String.class){
			res =  (T) node.getText();
		}
		if(clas == Date.class && !"".equals(node.getText().trim())){
			try {
				res = (T) DateUtil.dateFormat.parse(node.getText().trim());
			} catch (ParseException e) {
				logger.info("时间格式有误");
				e.printStackTrace();
			}
		}
		return res;
	}
	
	/**
	 * @param date
	 * @return
	 */
	public String getPlanXMLFile(Date date){
		return XMLProperty.getPlanDir() + DateUtil.getDayDateStr(date)+".xml";
	}
	
	/**
	 * @param date
	 * @return
	 */
	public String getPlanXMLFile(String date){
		return XMLProperty.getPlanDir() + date+".xml";
	}
}
